//
//  NIDatePickerCustomView.m
//  AIWAYS
//
//  Created by Marx on 2018/8/30.
//  Copyright © 2018年 wlq. All rights reserved.
//

#import "NIDatePickerCustomView.h"
#import "FontDefines.h"
@interface NIDatePickerCustomView()<UIPickerViewDelegate,UIPickerViewDataSource>
@end
@implementation NIDatePickerCustomView
{
    
    __weak IBOutlet UIView *contentView;
    __weak IBOutlet UIPickerView *datePicker;
    NSDate *selectDate;
    NSInteger startYear;
    NSInteger startMonth;
    NSInteger startDay;
    NSInteger startHour;
    NSInteger startMinute;
    
    NSInteger selectedYear;
    NSInteger selectedMonth;
    NSInteger selectedDay;
    NSInteger selectedHour;
    NSInteger selectedMinute;
    
    NSInteger totalYear;
    NSInteger totalMonth;
    NSInteger totalDay;
    NSInteger totalHour;
    NSInteger totalMinute;
    
}

-(void)awakeFromNib{
    [super awakeFromNib];
    [[NSBundle mainBundle] loadNibNamed:NSStringFromClass(self.class) owner:self options:nil];
    
    [self addSubview:contentView];
    
    contentView.translatesAutoresizingMaskIntoConstraints = NO;
    [self addConstraint:[NSLayoutConstraint constraintWithItem:contentView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeTop multiplier:1.0 constant:0]];
    [self addConstraint:[NSLayoutConstraint constraintWithItem:contentView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeBottom multiplier:1.0 constant:0]];
    
    [self addConstraint:[NSLayoutConstraint constraintWithItem:contentView attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeLeading multiplier:1.0 constant:0]];
    [self addConstraint:[NSLayoutConstraint constraintWithItem:contentView attribute:NSLayoutAttributeTrailing relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeTrailing multiplier:1.0 constant:0]];
    datePicker.delegate = self;
    datePicker.dataSource = self;
}

-(void)setCenterDate:(NSDate *)date
{
    selectDate = date;
}

- (void)show{
    [self loadStartTime];
    [self reloadComponents];
    self.hidden = NO;
    
}

- (void)close{
    self.hidden = YES;
}

#pragma mark - UIPickerView
- (IBAction)onCloseButtonOfPickViewClick:(id)sender{
    [self close];
}
- (IBAction)onClickCancel:(id)sender {
    [self close];
}

- (IBAction)onDoneButtonClick:(id)sender{
    [self close];
    if (self.delegate) {
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        //设置时间格式
        formatter.dateFormat = @"yyyyMMddHHmm";
        selectDate = [formatter dateFromString:[NSString stringWithFormat:@"%ld%02ld%02ld%02ld%02ld",selectedYear,selectedMonth,selectedDay,selectedHour,selectedMinute]];
        [self.delegate dateDidSelected:selectDate];
    }
}


-(void)loadStartTime
{
    NSDate *date = [selectDate laterDate:[NSDate date]];
    NSCalendar *calendar0 = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDateComponents *comps = [[NSDateComponents alloc] init];
    NSInteger unitFlags =  NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute;
    comps = [calendar0 components:unitFlags fromDate:date];
    NSInteger year=[comps year];
    NSInteger month=[comps month];
    NSInteger day=[comps day];
    NSInteger hour=[comps hour];
    NSInteger minute=[comps minute];
    
    startYear=year;
    startMonth=month;
    startDay=day;
    startHour=hour;
    startMinute=minute;
    
    selectedYear=year;
    selectedMonth=month;
    selectedDay=day;
    selectedHour=hour;
    selectedMinute=minute;
}
// 获取某年某月总共多少天
- (NSInteger)getDaysInYear:(NSInteger)year month:(NSInteger)imonth {
    if((imonth == 1)||(imonth == 3)||(imonth == 5)||(imonth == 7)||(imonth == 8)||(imonth == 10)||(imonth == 12))
        return 31;
    if((imonth == 4)||(imonth == 6)||(imonth == 9)||(imonth == 11))
        return 30;
    if((year%4 == 0)&&(year%100 != 0))
    {
        return 29;
    }
    if(year%100 == 0 && year%400 == 0)
    {
        return 29;
    }
    return 28;
}

-(void)reloadComponents
{
    totalYear = 20;
    if (selectedYear < startYear) {
        selectedYear = startYear;
        [datePicker selectRow:0 inComponent:0 animated:YES];
    }
    
    if (selectedYear == startYear) {
        totalMonth = 12 - startMonth + 1;
        if (selectedMonth < startMonth) {
            selectedMonth = startMonth;
        }
    }
    else
    {
        totalMonth = 12;
    }
    
    totalDay = [self getDaysInYear:selectedYear month:selectedMonth];
    if (selectedYear == startYear && selectedMonth == startMonth) {
        if (selectedDay < startDay) {
            selectedDay = startDay;
        }
        totalDay =  totalDay - startDay + 1;
    }
    if (selectedDay > [self getDaysInYear:selectedYear month:selectedMonth]) {
        selectedDay = [self getDaysInYear:selectedYear month:selectedMonth];
    }
    
    if (selectedYear == startYear && selectedMonth == startMonth && selectedDay == startDay) {
        if (selectedHour < startHour) {
            selectedHour = startHour;
        }
        totalHour =  24 - startHour;
    }
    else
    {
        totalHour = 24;
    }
    
    if (selectedYear == startYear && selectedMonth == startMonth && selectedDay == startDay
        && selectedHour == startHour) {
        if (selectedMinute <= startMinute) {
            selectedMinute = startMinute + 1;
        }
        totalMinute =  60 - startMinute -1;
    }
    else
    {
        totalMinute = 60;
    }
    NSLog(@"reloadComponents aaaaaaaaaaaaaaa");
    [datePicker reloadAllComponents];
    
    
    NSInteger row = (selectedMonth - 1) + totalMonth - 12;
    [datePicker selectRow:row inComponent:1 animated:NO];
    NSInteger row2 =  (selectedDay - 1) + totalDay - [self getDaysInYear:selectedYear month:selectedMonth];
    [datePicker selectRow:row2 inComponent:2 animated:NO];
    NSInteger row3 = selectedHour + totalHour - 24;
    [datePicker selectRow:row3 inComponent:3 animated:NO];
    NSInteger row4 = selectedMinute + totalMinute - 60;
    [datePicker selectRow:row4 inComponent:4 animated:NO];
}

#pragma mark - pickerView
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 5;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    switch (component) {
        case 0:
            return totalYear;
            break;
        case 1:
            return totalMonth;
            break;
        case 2:
            return totalDay;
            break;
        case 3:
            return totalHour;
            break;
        case 4:
            return totalMinute;
            break;
            
        default:
            return 0;
            break;
    }
}

- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component{
    return [UIApplication sharedApplication].keyWindow.bounds.size.width/10;
}
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(nullable UIView *)view{
    UIView *componentView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, pickerView.frame.size.width/5, [UIApplication sharedApplication].keyWindow.bounds.size.width/10)];
    UILabel *tempLabel = [[UILabel alloc] init];
    [componentView addSubview:tempLabel];
    tempLabel.textAlignment = NSTextAlignmentCenter;
    tempLabel.backgroundColor = [UIColor clearColor];
    tempLabel.textColor = [UIColor blackColor];
    switch (component) {
        case 0:
            tempLabel.text = [NSString stringWithFormat:@"%ld",startYear + row];
            break;
        case 1:
        {
            NSInteger month = 12 - totalMonth +row + 1;
            if (month < 10) {
                tempLabel.text = [NSString stringWithFormat:@"0%ld",month];
            }
            else
            {
                tempLabel.text = [NSString stringWithFormat:@"%ld",month];
            }
        }
            break;
        case 2:
        {
            NSInteger dayNum = [self getDaysInYear:selectedYear month:selectedMonth];
            NSInteger day = dayNum - totalDay +row + 1;
            if (day < 10) {
                tempLabel.text = [NSString stringWithFormat:@"0%ld",day];
            }
            else
            {
                tempLabel.text = [NSString stringWithFormat:@"%ld",day];
            }
        }
            break;
            
        case 3:
        {
            NSInteger hour = 24 - totalHour +row;
            if (hour < 10) {
                tempLabel.text = [NSString stringWithFormat:@"0%ld",hour];
            }
            else
            {
                tempLabel.text = [NSString stringWithFormat:@"%ld",hour];
            }
        }
            break;
        case 4:
        {
            NSInteger minute = 60 - totalMinute +row;
            if (minute < 10) {
                tempLabel.text = [NSString stringWithFormat:@"0%ld",minute];
            }
            else
            {
                tempLabel.text = [NSString stringWithFormat:@"%ld",minute];
            }
        }
            break;
        default:
            break;
    }
    
//    if (row == [pickerView selectedRowInComponent:0]) {
//        tempLabel.font = [UIFont systemFontOfSize:25];
//    }else{
//        tempLabel.font = [UIFont systemFontOfSize:2];
//    }
    tempLabel.font = UIFontPingFangMedium(15);
    [tempLabel sizeToFit];
    NSInteger x;
    if (component == 0) {
        x = componentView.frame.size.width/5;
    }else{
        x = componentView.frame.size.width/5 - tempLabel.frame.size.width;
    }
    [tempLabel setFrame:CGRectMake(x, (componentView.frame.size.height - tempLabel.frame.size.height)/2, tempLabel.frame.size.width, tempLabel.frame.size.height)];
    //删除分割线
    for (UIView *subView in pickerView.subviews) {
        if (subView.frame.size.height <= 1 && subView.frame.size.width >= pickerView.frame.size.width) {
            [subView setFrame:CGRectMake(20, subView.frame.origin.y, subView.frame.size.width - 40, subView.frame.size.height)];
            [subView setBackgroundColor:[UIColor darkGrayColor]];
            [subView setAlpha:0.8f];
        }
        
    }
    return componentView;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    switch (component) {
        case 0:
            selectedYear = startYear + row;
            break;
        case 1:
            selectedMonth = 12 - totalMonth +row + 1;;
            break;
        case 2:
        {
            
            NSInteger dayNum = [self getDaysInYear:selectedYear month:selectedMonth];
            selectedDay = dayNum - totalDay +row + 1;
        }
            break;
        case 3:
            selectedHour = 24 - totalHour +row;;
            break;
        case 4:
            selectedMinute = 60 - totalMinute +row;
            break;
            
        default:
            break;
    }
    [self reloadComponents];
}
@end
